package com.szholly.pro.watergas_server.ps.android.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;

import com.szholly.pro.watergas_server.water.monitorstation.zhuhai.ZhuhaiMonitorStationController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.common.util.RedisHelper;
import com.szholly.pro.watergas_server.ps.android.common.CommonSqlUtils;
import com.szholly.pro.watergas_server.ps.android.common.DateTime;
import com.szholly.pro.watergas_server.ps.android.common.ResultUtils;
import com.szholly.pro.watergas_server.ps.android.common.SecurityConfig;
import com.szholly.pro.watergas_server.ps.android.common.ValidUtils;
import com.szholly.pro.watergas_server.ps.android.service.MoveDataHistoryService;
import com.szholly.pro.watergas_server.ps.android.service.MoveDataRuntimeService;
import com.szholly.pro.watergas_server.ps.android.service.MoveDataService;
import com.szholly.pro.watergas_server.ps.android.service.MoveDataSurfaceService;
import com.szholly.pro.watergas_server.ps.android.service.MoveDataZhService;
import com.szholly.pro.watergas_server.ps.android.service.MoveDataWarnService;
import com.szholly.pro.watergas_server.ps.data.OperationGroupRow;
import com.szholly.utils.util.JSONUtils;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;

import net.sf.json.JSONArray;

/**
 * 污水接口控制器
 * 
 * 1.getRuntimeData 获取实时数据
 * 
 * 2.getHistoryDataInitData 获取历史数据初始化
 * 
 * @author joey
 *
 */
@Controller
@RequestMapping("/android/move/data/*")
public class MoveDataController implements ServletContextAware {
	@SuppressWarnings("unused")
	private ServletContext servletContext;
	@Autowired
	private MoveDataService mService;
	@Autowired
	private MoveDataZhService mZhService;
	@Autowired
	private MoveDataSurfaceService mSwService;
	@Autowired
	private MoveDataWarnService mWarnData;
	@Autowired
	private  MoveDataHistoryService mHistoryData;
	@Autowired
	private  MoveDataRuntimeService mRuntimeData;
	@Autowired
	private ZhuhaiMonitorStationController mZhuhaiMonitorStationController;
	@Override
	public void setServletContext(ServletContext arg0) {
		this.servletContext = arg0;
	}

	/**
	 * 数据初始化
	 */
	@RequestMapping("/getSplashInitData")
	@ResponseBody
	public String getSplashInitData() {
		try {
			List<RowBase> factoryList = MoveDataService.getFactoryList(null);
			List<RowBase> stationList = MoveDataService.getStationList(null,null);
			List<RowBase> parameterList = MoveDataService.getParameterList();
			List<RowBase> administrativeDivisionList = MoveDataService.getAdministrativeDivisionList();
			Map<String, Object> resultMap = new HashMap<>();
			resultMap.put("factoryList", factoryList);
			resultMap.put("stationList", stationList);
			resultMap.put("parameterList", parameterList);
			resultMap.put("administrativeDivisionList", administrativeDivisionList);
			return ResultUtils.getToastResult(resultMap);
		} catch (Exception e) {
			return ResultUtils.getToastResult(e);
		}
	}

	@RequestMapping("/getInitData")
	@ResponseBody
	public String getInitData(String userId) {
		try {
			ValidUtils.hasText(userId, "用户编号为空,站点获取失败");
			Map<String, Object> resultMap = new HashMap<>();
			SecurityConfig securityConfig = SecurityConfig.get(userId);
			if (securityConfig.containMoveDataZhuHai) {
				resultMap.put("factoryList",mZhService.getFactoryList(userId));
				resultMap.put("stationList", mZhService.getStationList(userId));
				resultMap.put("parameterList", mZhService.getParameterList());
				resultMap.put("administrativeDivisionList", mZhService.getAdministrativeDivisionList());
			}else if (securityConfig.containMoveDataSurface) {
				resultMap.put("factoryList",mSwService.getFactoryList(userId));
				resultMap.put("stationList", mSwService.getStationList(userId));
				resultMap.put("parameterList", mSwService.getParameterList());
				resultMap.put("administrativeDivisionList", mZhService.getAdministrativeDivisionList());
			}else {
				String groupCode = CommonSqlUtils.getGroupCode(userId);
				resultMap.put("factoryList",mService.getSewageFactoryList(groupCode));
				resultMap.put("stationList", MoveDataService.getStationList(groupCode, "0"));
				resultMap.put("parameterList", MoveDataService.getParameterList());
				resultMap.put("administrativeDivisionList", MoveDataService.getAdministrativeDivisionList());
			}		
			return ResultUtils.getToastResult(resultMap);
		} catch (Exception e) {
			return ResultUtils.getToastResult(e);
		}
	}

	/**
	 * 获取关注列表
	 */
	@RequestMapping("/getAttentionList")
	@ResponseBody
	public String getAttentionList(String userId) {
		try {
			List<String> attentionList = mService.getAttentionList(userId);
			return ResultUtils.getToastResult(attentionList);
		} catch (Exception e) {
			return ResultUtils.getToastResult(e);
		}
	}

	@RequestMapping("/addAttention")
	@ResponseBody
	public String addAttention(String userId, String stationId) {
		try {
			ValidUtils.hasText(userId, "用户编号为空,关注添加失败");
			ValidUtils.hasText(stationId, "站点编号为空,关注添加失败");
			List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
			String GUID = UUID.randomUUID().toString();
			parms.add(new GlobalParameter("GUID", GUID));
			parms.add(new GlobalParameter("STATION_CODE", stationId));
			parms.add(new GlobalParameter("USER_ID", userId));
			parms.add(new GlobalParameter("INFO", ""));
			String selectSql = "select count(*) as num from ATTENTION_INFO where station_code = @STATION_CODE and user_id =@USER_ID ";
			String Sql = "insert into ATTENTION_INFO(GUID,STATION_CODE,USER_ID,INFO) values (@GUID,@STATION_CODE,@USER_ID,@INFO)";
			List<RowBase> rows = DataUtil.getSelectRows(selectSql, parms);
			JSONArray list = JSONUtils.toJSONArray(rows);
			String num = list.getJSONObject(0).get("NUM").toString();
			if (num.equals("0")) {
				int i = DataUtil.ExecuteUpdateSql(Sql, parms);
				if (i == 0) {
					return ResultUtils.getToastResult("关注添加成功", true);
				} else {
					return ResultUtils.getToastResult("关注添加失败");
				}
			} else {
				return ResultUtils.getToastResult("关注添加失败", true);
			}
		} catch (Exception e) {
			return ResultUtils.getToastResult(e);
		}
	}

	@RequestMapping("/delAttention")
	@ResponseBody
	public String delAttention(String userId, String stationId) {
		try {
			ValidUtils.hasText(userId, "用户编号为空,关注取消失败");
			ValidUtils.hasText(stationId, "站点编号为空,关注取消失败");
			List<GlobalParameter> parms = new ArrayList<GlobalParameter>();
			parms.add(new GlobalParameter("userID", userId));
			parms.add(new GlobalParameter("stationId", stationId));
			String Sql = "delete from ATTENTION_INFO t where t.user_id = @userID and t.station_code = @stationId";
			int i = DataUtil.ExecuteUpdateSql(Sql, parms);
			if (i == 0) {
				return ResultUtils.getToastResult("关注取消成功", true);
			} else {
				return ResultUtils.getToastResult("关注取消失败");
			}
		} catch (Exception e) {
			return ResultUtils.getToastResult(e);
		}
	}

	@RequestMapping("/getRuntimeDataDetail")
	@ResponseBody
	public String getRuntimeDataDetail(String userId,String factoryCode) {
		try {
			ValidUtils.hasText(factoryCode, "工厂编号为空,实时数据获取失败");
			SecurityConfig securityConfig = SecurityConfig.get(userId);
			List<RowBase> rows;			
			if (securityConfig.containMoveDataZhuHai) {	
				String MnNumber = mZhuhaiMonitorStationController.getOpenedStationDeviceNum();
				String userStationId = RedisHelper.getInstance().getStationCodeByMN(MnNumber);
				List<RowBase> deviceList = mZhService.getDeviceList(userStationId);
				rows= mZhService.getRuntimeDataDetail(deviceList);
			}else {
				rows = mService.getRuntimeDataDetail(factoryCode);
			}
			return ResultUtils.getToastResult(rows);
		} catch (Exception e) {
			return ResultUtils.getToastResult(e);
		}
	}
	
	@RequestMapping("/getMultiFactoryRuntimeData")
	@ResponseBody
	public String getMultiFactoryRuntimeData(String userId,String factoryList) {
		try {
			ValidUtils.hasText(factoryList, "工厂编号列表不能为空");
			JSONArray factoryArray = JSONArray.fromObject(factoryList);
			List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();			
			SecurityConfig securityConfig = SecurityConfig.get(userId);
			if (securityConfig.containMoveDataZhuHai) {
				for (Object object : factoryArray) {
					String factoryCode = (String) object;
					List<RowBase> deviceList = mZhService.getDeviceList(factoryCode);
					List<Map<String, Object>> runtimeDataList = mZhService.getHomeRuntimeDataList(deviceList);
					resultList.addAll(runtimeDataList);
				}				
			}else {
				for (Object object : factoryArray) {
					String factoryCode = (String) object;
					List<Map<String, Object>> runtimeDataList = mService.getHomeRuntimeDataList(factoryCode);
					resultList.addAll(runtimeDataList);
				}
			}
			return ResultUtils.getToastResult(resultList);
		} catch (Exception e) {
			return ResultUtils.getToastResult(e);
		}
	}
	@RequestMapping("/getMultiRuntimeData")
	@ResponseBody
	public String getMultiRuntimeData(String userId,String factoryList){
		try {
			ValidUtils.hasText(factoryList, "工厂编号为空,实时数据获取失败");
			List<RowBase> rows;			
			String MnNumber = mZhuhaiMonitorStationController.getOpenedStationDeviceNum();
			String userStationId = RedisHelper.getInstance().getStationCodeByMN(MnNumber);
			List<RowBase> deviceList = mZhService.getDeviceList(userStationId);
			rows= mZhService.getRuntimeDataDetail(deviceList);
			return ResultUtils.getToastResult(rows);
		} catch (Exception e) {
			return ResultUtils.getToastResult(e);
		}
	}
	@RequestMapping("/getWarnData")
	@ResponseBody
	public String getWarnData(String token, String userId, String unit, String stationCode, String isRecover, String startTime, String endTime,
			String pageIndex) {
		try {
			ValidUtils.validateToken(token);
			ValidUtils.hasText(startTime, "起始时间为空，获取报警信息失败");
			ValidUtils.hasText(endTime, "结束时间为空，获取报警信息失败");
			int index = Integer.parseInt(pageIndex);
			ValidUtils.isTrue(index > 0, "页码有误,获取报警信息失败");
			SecurityConfig securityConfig = SecurityConfig.get(userId);
			Map<String, Object>warnMap;
			if (securityConfig.containMoveDataZhuHai) {
				warnMap = mWarnData.getZhWarnList(userId, unit, stationCode, isRecover, startTime, endTime, index);
			}else if (securityConfig.containMoveDataSewage) {
				warnMap = mWarnData.getSewageWarnList(userId, unit, stationCode, isRecover, startTime, endTime, index);
			}else if (securityConfig.containMoveDataSurface) {
				warnMap = mWarnData.getSurfaceWarnList(userId, unit, stationCode, isRecover, startTime, endTime, index);
			}else{
				warnMap = mWarnData.getSewageWarnList(userId, unit, stationCode, isRecover, startTime, endTime, index);
			}			
			return ResultUtils.getToastResult(warnMap);
		} catch (Exception e) {
			return ResultUtils.getToastResult(e);
		}
	}
	
	@RequestMapping("/getOneDayHourData")
	@ResponseBody
	public String getOneDayHourData(String token, String stationCode,String dateTime) {
		try{
			ValidUtils.hasText(stationCode, "站点编号为空，无法获取一天的小时数据");
			ValidUtils.hasText(dateTime, "日期为空，无法获取一天的小时数据");
			DateTime parseDateTime = DateTime.parse(dateTime, "yyyy-MM-dd HH:mm:ss");
			Map<String,Object>resultMap = new HashMap<>();
			List<RowBase> valueList = mHistoryData.getOneDayHourData(stationCode, parseDateTime);
			List<RowBase> alarmLimitList = mHistoryData.getAlarmLimit(stationCode);
			resultMap.put("valueList", valueList);
			resultMap.put("alarmLimitList", alarmLimitList);
			return ResultUtils.getToastResult(resultMap);
		}catch (Exception e) {
			return ResultUtils.getToastResult(e);
		}
	}
	
	@RequestMapping("/getOneDayMinData")
	@ResponseBody
	public String getOneDayMinData(String token, String stationCode,String dateTime) {
		try{
			ValidUtils.hasText(stationCode, "站点编号为空，无法获取一天的小时数据");
			ValidUtils.hasText(dateTime, "日期为空，无法获取一天的小时数据");
			DateTime parse = DateTime.parse(dateTime, "yyyy-MM-dd HH:mm:ss");
			Map<String,Object>resultMap = new HashMap<>();
			List<RowBase> valueList = mHistoryData.getOneDayMinData(stationCode, parse);
			List<RowBase> alarmLimitList = mHistoryData.getAlarmLimit(stationCode);
			resultMap.put("valueList", valueList);
			resultMap.put("alarmLimitList", alarmLimitList);
			return ResultUtils.getToastResult(resultMap);
		}catch (Exception e) {
			return ResultUtils.getToastResult(e);
		}
	}
	@RequestMapping("/getHistoryHourData")
	@ResponseBody
	public String getHistoryHourData(String token, String stationCode,String startTime,String endTime) {
		try{
			ValidUtils.hasText(stationCode, "站点编号为空，无法获取一天的小时数据");
			ValidUtils.hasText(startTime, "日期为空，无法获取一天的小时数据");
			ValidUtils.hasText(endTime, "日期为空，无法获取一天的小时数据");
			DateTime parseStartDateTime = DateTime.parse(startTime, "yyyy-MM-dd HH:mm:ss");
			DateTime parseEndDateTime = DateTime.parse(endTime, "yyyy-MM-dd HH:mm:ss");
			Map<String,Object>resultMap = new HashMap<>();
			List<RowBase> valueList = mZhService.getHistoryHourData(stationCode, parseStartDateTime,parseEndDateTime);
			List<RowBase> alarmLimitList = mHistoryData.getAlarmLimit(stationCode);
			resultMap.put("valueList", valueList);
			resultMap.put("alarmLimitList", alarmLimitList);
			return ResultUtils.getToastResult(resultMap);
		}catch (Exception e) {
			return ResultUtils.getToastResult(e);
		}
	}
	@RequestMapping("/getOneDayMinDataZh")
	@ResponseBody
	public String getOneDayMinDataZh(String token, String stationCode,String dateTime) {
		try{
			ValidUtils.hasText(stationCode, "站点编号为空，无法获取一天的小时数据");
			ValidUtils.hasText(dateTime, "日期为空，无法获取一天的小时数据");
			DateTime parse = DateTime.parse(dateTime, "yyyy-MM-dd HH:mm:ss");
			Map<String,Object>resultMap = new HashMap<>();
			List<RowBase> valueList = mZhService.getOneDayMinData(stationCode, parse);
			List<RowBase> alarmLimitList = mHistoryData.getAlarmLimit(stationCode);
			resultMap.put("valueList", valueList);
			resultMap.put("alarmLimitList", alarmLimitList);
			return ResultUtils.getToastResult(resultMap);
		}catch (Exception e) {
			return ResultUtils.getToastResult(e);
		}
	}
}
